package com.ht.medicaltreatment.activity

import android.bluetooth.BluetoothManager
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.githang.statusbar.StatusBarCompat
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.MoreAdapter
import com.ht.medicaltreatment.adapter.PDLoseAdapter
import com.ht.medicaltreatment.adapter.PDLoseLandAdapter
import com.ht.medicaltreatment.adapter.PDScanLandAdapter
import com.ht.medicaltreatment.bean.LandUIDBean
import com.ht.medicaltreatment.constant.DevicesSDK
import com.ht.medicaltreatment.serial.SerialPortUtils
import com.ht.medicaltreatment.utils.HandDevicesUitls
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.view.ReplaceDialog
import com.ht.medicaltreatment.viewmodel.PDScanViewModel
import com.xgst.lib.utils.showToast
import io.reactivex.rxjava3.disposables.Disposable
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.btnAgain
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.btnPositive
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.btnStopScan
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.imgLose
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.imgMore
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.imgState
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.recyclerView
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.recyclerViewLose
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.recyclerViewMore
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tabLayout
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvFour
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvLoseCount
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvMoreCount
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvNullCount
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvOriginalCount
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvOutCount
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvRealCount
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvSix
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvState
import kotlinx.android.synthetic.main.activity_inventory_scall_layout.tvTitleInfo


/**
 * 盘点-开始盘点- 横屏
 */
class InventoryScanLandActivity : BaseActivity(), OnItemClickListener {

    private val mViewModel by viewModels<PDScanViewModel>()

    private var startFlag : Boolean = false
    private var isOpenLose : Boolean = false
    private var isImgMore : Boolean = false
    //盒子的UID
    private lateinit var mBoxUid:String
    private var transportSampleBoxId = ""
    private lateinit var scanAdapter: PDScanLandAdapter
    //表格集合
    private val list = mutableListOf<LandUIDBean>()
    //多出来的试管放在这个集合中
    private val errorList = mutableListOf<String>()
    //空位置
    private val nullList = mutableListOf<LandUIDBean>()
    //实际扫描到的数量
    private var realCount = 0
    //缺失的试管
    private var loseCountList = mutableListOf<LandUIDBean>()
    //用来记录每个uid的位置
    private val mUidMap = mutableMapOf<String,LandUIDBean>()
    private lateinit var dialog : ReplaceDialog
    private var isReplace = false

    private val loseAdapter = PDLoseLandAdapter()
    private val moreAdapter = MoreAdapter()
    private var orderId = 0
    private var device = DevicesSDK.devices
    private lateinit var bluetoothManager:BluetoothManager

    private var boxCol = 0

    override fun getLayoutId() = R.layout.activity_inventory_scall_layout

    override fun init() {
        StatusBarCompat.setStatusBarColor(this,getColor(R.color.white),true)
        bluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager

        SerialPortUtils.initDevice()

        dialog = ReplaceDialog(this)
        mBoxUid = intent.getStringExtra("uid")?:""

        orderId = intent.getIntExtra("orderId",0)
        scanAdapter = PDScanLandAdapter()

        recyclerViewLose.layoutManager = LinearLayoutManager(this)
        recyclerViewLose.adapter = loseAdapter

        recyclerViewMore.layoutManager = LinearLayoutManager(this)
        recyclerViewMore.adapter = moreAdapter
        loseAdapter.setOnItemClickListener(this)
        moreAdapter.setOnItemClickListener(this)

        val tab1 = tabLayout.newTab()
        tab1.setText("盘点结果")
        tabLayout.addTab(tab1)

        val tab2 = tabLayout.newTab()
        tab2.setText("查询样本")
        tabLayout.addTab(tab2)

        initData(false)
        initClick()

        initListener()
    }

    /**
     * 获取数据
     */
    private fun initData(isReset:Boolean) {
        showProgress()
        tvState.setText("样品待检验…")
        tvState.setTextColor(getColor(R.color.color22_50))
        mViewModel.scanData(mBoxUid, "$orderId", {
            boxCol = it.rfidSampleBox.sampleBoxStru.structureCol
            recyclerView.layoutManager = GridLayoutManager(this, boxCol)
            recyclerView.adapter = scanAdapter
            //转运样本盒id
            transportSampleBoxId  = "${it.inventorySampleBox.id}"
            tvTitleInfo.text = "实际盘点样本信息：${it.rfidSampleBox.name}"
            list.clear()
            mUidMap.clear()
            it.rfidSampleBox.rfidSampleVOList?.forEach {
                /**
                 * 样本盒中，有些孔位有试管，有些孔位没有试管。it.uid为空，就是没有试管的
                 * list集合的目的是按照行 列 把adapter填充满，正常都是白色
                 * 如果有uid的，颜色是蓝色，这样一个样本盒就出来了。
                 */
               val bean = LandUIDBean(
                    originalLocation = it.location,
                    originalUid = it.uid,
                    rfidSampleId = it.rfidSampleId,
                    type = 0,
                    name = it.name)
                list += bean
                //TODO 不一定需要
                mUidMap.put(it.uid!!,bean)
            }
            tvOriginalCount.text = "${mUidMap.size}"
            scanAdapter.setNewInstance(list)
            dismissProgress()
            if(isReset){
                //重新核验
                startScan()
            }
        }, {
            dismissProgress()
            showToast(it)
        })
    }

    private fun initClick() {
        //缺失样本数量
        tvFour.setOnClickListener {
            if(isOpenLose){
                imgLose.rotation = 0f
                recyclerViewLose.visibility = View.GONE
            }else{
                imgLose.rotation = 90f
                recyclerViewLose.visibility = View.VISIBLE
            }
            isOpenLose = !isOpenLose
        }

        //不属于该样本盒的样本数量
        tvSix.setOnClickListener {
            if(isImgMore){
                imgMore.rotation = 0f
                recyclerViewMore.visibility = View.GONE
            }else{
                imgMore.rotation = 90f
                recyclerViewMore.visibility = View.VISIBLE
            }
            isImgMore = !isImgMore
        }

        dialog.setOnDismissListener {
            btnStopScan.text = "开始扫描"
            if(DevicesSDK.HAND == device){
                HandDevicesUitls.stopScan()
            }else{
                ScanUtils.close()
            }
        }

        //确认
        btnPositive.setOnClickListener {
            if(loseCountList.size > 0 || errorList.size > 0){
                showToast("盘点检验有误")
                return@setOnClickListener
            }
            showProgress()
            mViewModel.submit(transportSampleBoxId,{
                dismissProgress()
                showToast("提交成功")

                btnPositive.text = "已提交"
                btnPositive.isEnabled = false
                btnPositive.setBackgroundColor(getColor(R.color.color97))

                btnAgain.isEnabled = false
                btnAgain.setBackgroundColor(getColor(R.color.color97))

                setResult(RESULT_OK)
                finish()
            },{
                dismissProgress()
                showToast(it)
            })
        }

        //重新核验
        btnAgain.setOnClickListener {
            reset()
        }

        // 开始盘点
        btnStopScan.setOnClickListener {
            startScan()
        }

        tvTitleInfo.setOnClickListener {
            scanAdapter.data.forEach {
                LogUtils.i("old: ${it.originalUid}","new: ${it.newUid}"
                    ,"originalLocation: ${it.originalLocation}","newLocation: ${it.newLocation}")
            }
        }
    }

    private fun startScan() {
        startFlag = true
        SerialPortUtils.startUHF()
    }

    /**
     * 扫描结果
     */
    private fun initListener() {
        SerialPortUtils.setListener { uid, row, col ->
            if(uid.isNotEmpty()){
                val position = row * boxCol + col
                LogUtils.i("扫描到UID  :  $uid    row:$row    col:$col     position:$position")
                checkUID(uid,position)
            }else{
                //没有数据了，开始计算结果
                checkScanResult()
            }
        }
    }

    //处理扫描出来的UID
    fun checkUID(newUID:String,position:Int){
        if(isReplace){
            //stopScan()
            dialog.setUID(newUID)
            return
        }
        if(scanAdapter.data.size <= position){
            return
        }
        SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
        val value = mUidMap[newUID]
        val bean = scanAdapter.getItem(position)
        bean.newUid = newUID
        bean.newLocation = position
        bean.type = 1
        scanAdapter.notifyItemChanged(position)

        if(value == null){
            //不是这个样本盒内的管子
            errorList += newUID!!
            tvMoreCount.text = "${errorList.size}"
        }
    }

    private fun reset() {
        tvRealCount.setText("0")
        tvOutCount.setText("0")
        tvLoseCount.setText("0")
        tvNullCount.setText("0")
        tvMoreCount.setText("0")
        isReplace = false
        loseCountList.clear()
        errorList.clear()
        imgState.visibility = View.GONE
        loseAdapter.setNewInstance(null)
        moreAdapter.setNewInstance(null)
        initData(true)
        btnStopScan.text = "停止扫描"
    }

    private var disposable: Disposable?=null


    /**
     * 开始检测扫描结果
     */
    private fun checkScanResult() {
        nullList.clear()
        loseCountList.clear()
        realCount = 0
        val adapterData = scanAdapter.data
        adapterData.forEach {
            if(it.originalUid != null && it.newUid == null){
                loseCountList += it
                tvLoseCount.text = "${loseCountList.size}"
            }else{
                realCount++
            }
        }

        /*if(loseCountList.size > 0){
            //如果有缺失，其他空位置全部变红
            adapterData.forEach {
                if(it.type == 0){
                    val bean = RfidSampleVO(
                        location = it.location,
                        uid = it.uid,
                        rfidSampleId = it.rfidSampleId,
                        status = it.status,
                        type = 3,
                        name = it.name)
                    scanAdapter.setData(it.location-1,bean)
                }
            }
        }*/

        tvLoseCount.text = "${loseCountList.size}"
        loseAdapter.setNewInstance(loseCountList)

        //错误的uid
        moreAdapter.setNewInstance(errorList)
        /*if(errorList.size > 0 && nullList.size > 0){
            //有多出来的试管，并且也有空余的格子
            nullList.forEach {
                scanAdapter.setData(it.location-1,it)
            }
            moreAdapter.setNewInstance(errorList)
        }*/

        tvRealCount.text = "${realCount+errorList.size}"

        imgState.visibility = View.VISIBLE
        if(errorList.size > 0 || loseCountList.size > 0){
            tvState.text = "检验异常"
            imgState.setBackgroundResource(R.drawable.icon_check_error)
            tvState.setTextColor(getColor(R.color.yellow))
        }else{
            tvState.text = "检验无误"
            imgState.setBackgroundResource(R.drawable.icon_check_ok)
            tvState.setTextColor(getColor(R.color.green))
        }
    }

    //停止扫描
    fun stopScan(){
        btnStopScan.text = "开始扫描"
        if(DevicesSDK.HAND == device){
            HandDevicesUitls.stopScan()
        }else{
            ScanUtils.close()
        }

        checkScanResult()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if (adapter is PDLoseAdapter){

            if(adapter.data.size == 0){
                return
            }
            isReplace = true
            val bean = adapter.data.get(position)
            startScan()
            //替换芯片
            dialog.showDialog(position,{newUID,position ->
                dialog.dismiss()

                //点击确认替换后，关闭扫描
                btnStopScan.text = "开始扫描"
                if(DevicesSDK.HAND == device){
                    HandDevicesUitls.stopScan()
                }else{
                    ScanUtils.close()
                }

                showProgress()
                isReplace = false
                mViewModel.replace("${bean.uid}",newUID,{
                    dismissProgress()
                    if(mUidMap.containsKey(bean.uid)){
                        val location = mUidMap[bean.uid]?.originalLocation
                        val bean = mUidMap[bean.uid]!!
                        loseAdapter.removeAt(position)
                        tvLoseCount.setText("${loseAdapter.data.size}")
                        bean.originalUid = newUID
                        mUidMap[newUID] = bean
                        scanAdapter.setData(location!!-1,mUidMap[newUID]!!)

                        if(loseAdapter.data.size == 0 && moreAdapter.data.size == 0){
                            tvState.text = "检验无误"
                            imgState.setBackgroundResource(R.drawable.icon_check_ok)
                            tvState.setTextColor(getColor(R.color.green))
                            scanAdapter.data.forEach{
                                if(it.type == 3){
                                    it.type = 0
                                    //scanAdapter.setData(it.location-1,it)
                                }
                            }
                        }
                    }
                },{
                    dismissProgress()
                    showToast(it)
                })
            })
        }else if(adapter is MoreAdapter){
            //不属于该样本盒，获取每个试管的名字
            showProgress()
            mViewModel.searchName(errorList,{
                dismissProgress()
                moreAdapter.setNewInstance(it)
            },{
                dismissProgress()
                showToast(it)
            })
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if(disposable?.isDisposed == false){
            disposable?.dispose()
        }
        if(device == DevicesSDK.HAND){
            HandDevicesUitls.close()
        }else{
            ScanUtils.close()
        }
    }
}